package br.gendi.rcp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.part.ViewPart;

import br.gendi.beans.BaseGenomica;
import br.gendi.dialog.ConfiguracoesBases;

public class NavigationView extends ViewPart {

	public static final String ID = "br.gendi.rcp.navigationView";

    private ToolBar toolBar = null;
    
    public void createPartControl(final Composite parent) {
    	GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = false;
		gridData.verticalAlignment = GridData.BEGINNING;
		
		toolBar = new ToolBar(parent, SWT.FLAT | SWT.WRAP | SWT.H_SCROLL);
		toolBar.setLayoutData(gridData);
		try {
			carregarItens();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
	
		parent.getShell().addListener(SWT.Resize, new Listener() {
			public void handleEvent(Event e) {
				Rectangle rect = parent.getShell().getClientArea();
				Point size = toolBar.computeSize(rect.width, SWT.DEFAULT);
				toolBar.setSize(size);
			}
		});
    }

	public void carregarItens() throws FileNotFoundException, IOException, ClassNotFoundException {
		for (int i=0; i<toolBar.getItemCount(); i++) {
			toolBar.getItem(i).dispose();
		}
		
		File f = new File(".\\saves\\");
		if (!f.exists())
			f.mkdirs();
		File lista[] = f.listFiles();
		Image img = null;

		if (lista == null || lista.length == 0)
			return;

		for (int i=0; i<lista.length; i++) 
		{
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(lista[i])); 
			final BaseGenomica base = (BaseGenomica)in.readObject();
			ToolItem toolItem1 = new ToolItem(toolBar, SWT.PUSH);
			toolItem1.setText(base.getTitulo());
			toolItem1.setImage(new Image(Display.getCurrent(), getClass().getResourceAsStream("/images/dnadna.png")));
			toolItem1.addSelectionListener(new SelectionListener() {
				public void widgetDefaultSelected(SelectionEvent arg0) {
				}
				public void widgetSelected(SelectionEvent arg0) {
					ConfiguracoesBases c = new ConfiguracoesBases(base);
				}
			});
			
		}
	}
	
	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		//viewer.getControl().setFocus();
	}
}